package cn.devhost.controller;

import cn.devhost.ServerInfo;
import cn.lingyangwl.framework.core.response.Resp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * @author shenguangyang
 */
@Slf4j
@RestController
public class IndexController {

    @GetMapping("")
    public Resp<ServerInfo> serverInfo() {
        String ip;
        String hostname;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            ip = addr.getHostAddress();
            hostname = addr.getHostName();
        } catch (UnknownHostException e) {
            log.error("Can't find out address: " + e.getMessage());
            ip = "UNKNOWN";
            hostname = "UNKNOWN";
        }
        if (ip.equals("127.0.0.1") || ip.equals("::1") || ip.equals("UNKNOWN")) {
            try {
                Process process = Runtime.getRuntime().exec("hostname -i");
                if (process.waitFor() == 0) {
                    ip = new String(IOUtils.toByteArray(process.getInputStream()), StandardCharsets.UTF_8);
                }
                process = Runtime.getRuntime().exec("hostname");
                if (process.waitFor() == 0) {
                    hostname = (new String(IOUtils.toByteArray(process.getInputStream()), StandardCharsets.UTF_8)).trim();
                }
            } catch (Exception e) {
                log.warn("get hostname failed {}", e.getMessage());
            }
        }
        log.info("ip {} hostname {}", ip, hostname);
        return Resp.ok(ServerInfo.builder().ip(ip).hostname(hostname).build());
    }
}
